package com.lcq.demo;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.junit.Test;
import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.w3c.dom.Node;

import java.io.*;
import java.util.List;

/**
 * @ClassName WordPictureTest
 * @Description
 * @Author lichuanqi
 * @Date 2022/3/16 17:56
 * @Version 1.0
 **/
public class WordPictureTest {
    public static void main(String[] args) throws IOException, InvalidFormatException {
        // 读取word模板
        File inputFile = new File("E:/test/pictureTest.docx");
        FileInputStream fileInputStream = new FileInputStream(inputFile);
        XWPFDocument document = new XWPFDocument(fileInputStream);
        List<IBodyElement> bodyElements = document.getBodyElements();
        int curP = 0;
        IBodyElement bodyElement = bodyElements.get(0);
        XWPFParagraph paragraph = document.getParagraphArray(curP);
        XWPFRun run = paragraph.getRuns().get(0);
        XWPFPicture picture = run.getEmbeddedPictures().get(0);
        XWPFPictureData pictureData = picture.getPictureData();
        CTPicture ctPicture = picture.getCTPicture();
        Node domNode = ctPicture.getDomNode();
        CTPictureNonVisual nvPicPr = ctPicture.getNvPicPr();
        CTShapeProperties spPr = ctPicture.getSpPr();
        byte[] data = pictureData.getData();
        String pictureText = run.getPictureText();

        XWPFParagraph paragraph1 = document.createParagraph();
        paragraph1.getCTP().setPPr(paragraph.getCTP().getPPr());
        XWPFRun run1 = paragraph1.createRun();
        run1.getCTR().setRPr(run.getCTR().getRPr());
        //run1.getCTR().setPictArray(run.getCTR().getPictArray());



        run1.addPicture(new ByteArrayInputStream(data),
                pictureData.getPictureType(),
                pictureData.getFileName(),
                1406*3600,
                1199*3600);

        document.write(new FileOutputStream(new File("E:/test/pictureOut.docx")));
    }
}
